package com.demo.feifan.aspect;

import com.demo.feifan.annotation.DynamicDataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 数据源切换切面
 */
@Aspect
@Component
public class DataSourceAspect {
    /**
     * 切换数据源
     * @param point
     * @param dynamicDataSource
     */
    @Before("@annotation(dynamicDataSource)")
    public void before(JoinPoint point, DynamicDataSource dynamicDataSource) {
        String dataSource = dynamicDataSource.value();
        DynamicDataSourceContextHolder.setDataSource(dataSource);
    }

    /**
     * 抛出异常之后清理数据源
     * @param point
     * @param dynamicDataSource
     * @param e
     */
    @AfterThrowing(pointcut = "@annotation(dynamicDataSource)", throwing = "e")
    public void afterThrowing(JoinPoint point, DynamicDataSource dynamicDataSource, Throwable e) {
        DynamicDataSourceContextHolder.clearDataSource();
    }
}